import IconFont from '@/IconFontAl';
import defPic from '@/assets/imgs/default_head.png';
import { Checkbox, Empty, Radio, Skeleton } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import classNames from 'classnames';

import {
  forwardRef,
  useImperativeHandle,
  useLayoutEffect,
  useMemo,
  useState,
} from 'react';
import CrumbList from './CrumbList';
import {
  ChoiceListRef,
  CrumbItem,
  IOrgItem,
  IOrgPerson,
  OrgChoiceListProps,
  TChoiceStaffValue,
  TPerson,
  orgRequestParams,
} from './interface';

import { getOrgCheckboxStaObj } from './utils';

const OrgChoiceList = forwardRef<ChoiceListRef, OrgChoiceListProps>(
  (props, ref) => {
    const {
      defaultValue,
      onOrgChoiceChange,
      onOrgChoiceChangeBatch,
      orgRequest,
      requestParams,
      keyWord,
      prefixCls,
      onlyChoicePeople,
      choiceBtn,
    } = props;
    const { entId } = requestParams;
    // const crumbRef = useRef
    const [loading, showLoading] = useState<boolean>(false);
    const [selectedValues, setSelectedValues] = useState<TChoiceStaffValue[]>(
      defaultValue || [],
    );
    //面包屑
    const [orgLv, setOrgLv] = useState<CrumbItem[]>([]);

    //定义列表数据
    const [orgList, setOrgList] = useState<IOrgItem[]>([]);
    const [orgStaffList, setOrgStaffList] = useState<TPerson[]>([]);

    // 获取部门(type===1)、部门人员(type===2) 列表
    const getOrgList = (
      params: orgRequestParams,
      noneeShowLoading?: boolean,
    ) => {
      if (!noneeShowLoading) {
        showLoading(true);
      }
      return orgRequest(params)
        .then((resData1) => {
          // console.log('--getOrgList--resData1--:', resData1);
          let tempOrgList: IOrgItem[] = [];
          const tempOrgStaffList: TPerson[] = [];
          resData1?.forEach((data) => {
            const { type, partsList = [] } = data;
            if (type === 1) {
              (partsList as IOrgItem[]).forEach((listItem) => {
                tempOrgList.push({
                  ...listItem,
                  combineId: `${params.departId}_${listItem.guid}`,
                });
              });
            } else if (type === 2) {
              partsList.forEach((listItem) => {
                const { guid, name, phone, hdpic } = listItem as IOrgPerson;
                tempOrgStaffList.push({
                  combineId: `${params.departId}_${guid}`, // 注：如果同一个人在不同部门，采用combineId = personId + departId 标记唯一性
                  personId: guid,
                  personName: name,
                  phone,
                  hdpic,
                });
              });
            }
          });
          setOrgList(tempOrgList);
          setOrgStaffList(tempOrgStaffList);
        })
        .finally(() => {
          showLoading(false);
        });
    };

    //删除选中,re中的函数谨慎用useCallback包裹
    const handleDelete = (selectedItem: TChoiceStaffValue) => {
      const tempSelectedValues = selectedValues;
      const exitIndex = tempSelectedValues.findIndex(
        (valItem) => valItem.combineId === selectedItem.combineId,
      );
      if (exitIndex > -1) {
        tempSelectedValues.splice(exitIndex, 1);
        onOrgChoiceChange('delete', selectedItem);
        setSelectedValues([...tempSelectedValues]);
      }
    };

    //搜索
    const handleSearch = (keyWord: string | undefined) => {
      const departId = orgLv[orgLv.length - 1].guid;
      getOrgList({ entId, departId, keyWord });
    };

    useImperativeHandle(ref, () => ({
      search: handleSearch,
      delete: handleDelete,
      resetSelectedValues: (newSelValues: TChoiceStaffValue[]) => {
        setSelectedValues(newSelValues);
      },
    }));

    useLayoutEffect(() => {
      showLoading(true);
      orgRequest({ entId }).then((resData) => {
        const partsDetail =
          resData && resData[0] && resData[0].partsList
            ? resData[0].partsList[0]
            : undefined;
        // console.log('--OrgChoiceList--partsDetail--:', partsDetail);
        if (!partsDetail) return;
        const { name, guid } = partsDetail;
        setOrgLv([{ guid, name }]);
        // setOrgLv([{ guid, name }, { guid: '83d898a37d0d4becbdc91a8ff135a42f', name: '加人了' }, { guid: '401662cd3a1b4d4aa63d07a98639d275', name: '加人了的一部我和我的祖国一刻也不能' }])
        getOrgList({ entId, departId: guid }, true);
      });
    }, []);

    //面包屑
    const handleCrumbClick = (currCurmb: CrumbItem) => {
      // console.log('--currCurmb--:', currCurmb);
      const { guid } = currCurmb;
      const currIndex = orgLv.findIndex((lvItem) => lvItem.guid === guid);
      if (currIndex > -1) {
        orgLv.splice(currIndex + 1);
        setOrgLv([...orgLv]);
        getOrgList({ entId, departId: guid, keyWord });
      }
    };

    //下一级
    const handOrgChild = (e: React.MouseEvent, orgItem: IOrgItem) => {
      e.stopPropagation();
      const { guid, name } = orgItem;
      getOrgList({ entId, departId: guid, keyWord }).then(() => {
        orgLv.push({ guid, name });
        setOrgLv(orgLv);
      });
    };
    //全选
    // 当<Checkbox checked={true} />时，点击Checkbox e.target.checked永远是false
    const handleAllChoiceChange = (e: CheckboxChangeEvent) => {
      const allChecked = e.target.checked;

      const tempOperationList: TChoiceStaffValue[] = [];
      const tempSelectedValues = selectedValues;
      if (!onlyChoicePeople) {
        orgList.forEach((orgItem) => {
          const existOrgItemIndex = tempSelectedValues.findIndex(
            (selItem) => selItem.combineId === orgItem.combineId,
          );
          const tempSelItem: TChoiceStaffValue = {
            choiceType: 'org',
            guid: orgItem.guid,
            name: orgItem.name,
            combineId: orgItem.combineId!,
          };
          if (existOrgItemIndex < 0 && allChecked) {
            //选中不存在
            tempSelectedValues.push(tempSelItem);
            tempOperationList.push(tempSelItem);
          }
          if (existOrgItemIndex > -1 && !allChecked) {
            //取消选中已存在
            tempSelectedValues.splice(existOrgItemIndex, 1);
            tempOperationList.push(tempSelItem);
          }
        });
      }
      orgStaffList.forEach((orgStaffItem) => {
        const existOrgStaffItemIndex = selectedValues.findIndex(
          (selItem) => selItem.combineId === orgStaffItem.combineId,
        );
        const tempSelItem: TChoiceStaffValue = {
          choiceType: 'org',
          ...orgStaffItem,
        };
        if (existOrgStaffItemIndex < 0 && allChecked) {
          tempSelectedValues.push(tempSelItem);
          tempOperationList.push(tempSelItem);
        }
        if (existOrgStaffItemIndex > -1 && !allChecked) {
          tempSelectedValues.splice(existOrgStaffItemIndex, 1);
          tempOperationList.push(tempSelItem);
        }
      });

      onOrgChoiceChangeBatch(allChecked ? 'add' : 'delete', tempOperationList);
      setSelectedValues([...tempSelectedValues]);
    };

    //当前行选中、取消选中
    const choiceItem = (
      type: 'guid' | 'personId',
      item: any, //IOrgItem & TPerson,
    ) => {
      if (type === 'guid' && onlyChoicePeople) return;
      let tempSelectedValues = selectedValues;
      const exitIndex = tempSelectedValues.findIndex(
        (valItem) => valItem.combineId === item.combineId,
      );
      const tempValItem: TChoiceStaffValue =
        type === 'guid'
          ? {
              choiceType: 'org',
              guid: item.guid,
              name: item.name,
              combineId: item.combineId,
            }
          : { choiceType: 'org', ...item };
      if (exitIndex < 0) {
        if (choiceBtn === 'checkbox') {
          tempSelectedValues.push(tempValItem);
        } else {
          tempSelectedValues = [tempValItem];
        }
      } else {
        tempSelectedValues.splice(exitIndex, 1);
      }
      onOrgChoiceChange(exitIndex < 0 ? 'add' : 'delete', tempValItem);
      // console.log('--选中取消选中--tempSelectedValues--：', tempSelectedValues)
      setSelectedValues([...tempSelectedValues]);
    };

    //全选checkbox是否显示
    const allCheckBoxShow = useMemo(() => {
      let tempShow = false;
      if (choiceBtn === 'checkbox') {
        if (onlyChoicePeople) {
          if (orgStaffList.length > 0) {
            tempShow = true;
          }
        } else {
          if (orgList.length > 0 || orgStaffList.length > 0) {
            tempShow = true;
          }
        }
      }
      return tempShow;
    }, [onlyChoicePeople, choiceBtn, orgList, orgStaffList]);

    return (
      <div className={`${prefixCls}-choice`}>
        {orgLv.length > 0 && (
          <CrumbList
            crumbList={orgLv}
            onCrumbClick={handleCrumbClick}
            prefixCls={prefixCls}
          />
        )}
        {allCheckBoxShow && (
          <Checkbox
            indeterminate={
              getOrgCheckboxStaObj(
                selectedValues,
                orgList,
                orgStaffList,
                onlyChoicePeople,
              ).indeterminate
            }
            onChange={handleAllChoiceChange}
            checked={
              getOrgCheckboxStaObj(
                selectedValues,
                orgList,
                orgStaffList,
                onlyChoicePeople,
              ).checked
            }
            style={{ marginLeft: '5px' }}
          >
            全选
          </Checkbox>
        )}

        <ul className="choice_list">
          <Skeleton
            loading={loading}
            active
            paragraph={{ rows: 4, width: 296 }}
            title={false}
          >
            {orgList.map((orgItem) => (
              <li
                key={orgItem.combineId}
                className="list_other_item"
                onClick={() => {
                  choiceItem('guid', orgItem);
                }}
              >
                {choiceBtn === 'checkbox' && !onlyChoicePeople && (
                  <Checkbox
                    checked={
                      selectedValues.findIndex(
                        (valItem) => valItem.guid === orgItem.guid,
                      ) > -1
                        ? true
                        : false
                    }
                    style={{ marginLeft: '5px' }}
                  />
                )}

                {choiceBtn === 'radio' && !onlyChoicePeople && (
                  <Radio
                    checked={
                      selectedValues.findIndex(
                        (valItem) => valItem.guid === orgItem.guid,
                      ) > -1
                        ? true
                        : false
                    }
                    style={{ marginLeft: '5px', marginInlineEnd: '0px' }}
                  />
                )}
                <div
                  className="item_center"
                  style={{ marginLeft: onlyChoicePeople ? '5px' : '0px' }}
                >
                  <IconFont
                    type="icon-chengyuanyubumen"
                    className="center_icon"
                  />
                  <p className="center_text">{orgItem.name}</p>
                </div>
                <p
                  className={classNames('item_right', {
                    ['disabled']:
                      (!orgItem.lowerLevel && !orgItem.num) ||
                      selectedValues.findIndex(
                        (valItem) => valItem.guid === orgItem.guid,
                      ) > -1,
                  })}
                  onClick={(e) => {
                    (orgItem.lowerLevel || orgItem.num) &&
                      selectedValues.findIndex(
                        (valItem) => valItem.guid === orgItem.guid,
                      ) < 0 &&
                      handOrgChild(e, orgItem);
                  }}
                >
                  下级
                </p>
              </li>
            ))}
            {orgStaffList.map((orgStaffItem) => (
              <li
                key={orgStaffItem.combineId}
                className="list_staff_item"
                onClick={() => {
                  choiceItem('personId', orgStaffItem);
                }}
              >
                {choiceBtn === 'checkbox' ? (
                  <Checkbox
                    checked={
                      selectedValues.findIndex(
                        (valItem) =>
                          valItem.combineId === orgStaffItem.combineId,
                      ) > -1
                        ? true
                        : false
                    }
                    style={{ marginLeft: '5px' }}
                  />
                ) : (
                  <Radio
                    checked={
                      selectedValues.findIndex(
                        (valItem) =>
                          valItem.combineId === orgStaffItem.combineId,
                      ) > -1
                        ? true
                        : false
                    }
                    style={{ marginLeft: '5px', marginInlineEnd: '0px' }}
                  />
                )}
                <div className="item_person">
                  <img
                    className="person_avatar"
                    src={orgStaffItem.hdpic || defPic}
                    alt="头像"
                  />
                  <p className="person_text">
                    <span>{orgStaffItem.personName}</span>
                    <span>({orgStaffItem.phone})</span>
                  </p>
                </div>
              </li>
            ))}
            {!loading && orgList!.length <= 0 && orgStaffList!.length <= 0 && (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={false} />
            )}
          </Skeleton>
        </ul>
      </div>
    );
  },
);

export default OrgChoiceList;
